<template>
  <div>
    <el-table
      ref="tableRef"
      :data="[customerInfo]"
      style="width: 100%;margin-top: 10px;">
      <el-table-column property="province" label="省份" align="center" width="80" />
      <el-table-column property="name" label="名称" align="center" width="120" />
      <el-table-column property="shortName" label="简称" align="center" width="80" />
      <el-table-column property="taxNumber" label="统一社会信用代码" align="center" width="130" />
      <el-table-column property="address" label="地址" align="center" width="120" />
      <el-table-column property="registeredAddress" label="注册地址" align="center" width="120" />
      <el-table-column property="bank" label="开户银行" align="center" width="120" />
      <el-table-column property="bankNumber" label="银行账号" align="center" width="120" />
      <el-table-column property="phone" label="电话号码" align="center" width="120" />
      <el-table-column property="taxRate" label="税率" align="center" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_tax_rate" :value="scope.row.taxRate" />
        </template>
      </el-table-column>
      <el-table-column property="webAddress" label="网址" align="center" width="120" />
      <el-table-column property="legalPerson" label="法定代表人" align="center" width="100" />
<!--      <el-table-column property="unit" label="举办单位/业务主管单位" align="center" width="180" />-->
      <el-table-column property="remark" label="经营范围" align="center">
        <template slot-scope="scope">
          <div v-html="scope.row.remark.replace(/\n/g, '<br/>')"></div>
<!--          <el-tooltip class="item" effect="dark" :content="scope.row.remark" placement="top">-->
<!--            <div class="oneLine">{{ scope.row.remark }}</div>-->
<!--          </el-tooltip>-->
        </template>
      </el-table-column>
    </el-table>

    <el-form ref="queryFormRef" :inline="true" :model="queryParams" style="margin-top: 20px" class="demo-form-inline" v-hasPermi="['md:department:query']">
      <el-form-item label="二级部门" prop="name">
        <el-input v-model.trim="queryParams.name" clearable :maxlength="50" size="small" placeholder="请输入二级部门"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" v-hasPermi="['md:department:query']" @click="searchHandler">查询</el-button>
        <el-button icon="el-icon-refresh-right" size="mini" v-hasPermi="['md:department:query']" @click="resetForm('queryFormRef')">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="grid-content bg-purple">
      <el-button plain type="primary" size="mini" icon="el-icon-plus" v-hasPermi="['md:department:add']" @click="openDialog(null)">增加</el-button>
      <!--          <el-button plain type="warning" size="mini" icon="el-icon-download" v-hasPermi="['md:school:export']" @click="exportHandler">导出</el-button>-->
    </div>

    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="tableData"
      highlight-current-row
      max-height="450"
      v-horizontal-scroll="'auto'"
      @current-change="handleCurrentChange"
      style="width: 100%;margin-top: 10px;">
      <el-table-column
        type="index"
        width="50"
        align="center"
        label="序号"
      >
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column
        property="name"
        label="二级部门"
        align="center"
        width="120"
      />
      <el-table-column
        property="major"
        label="相关专业"
        align="center"
        width="300"
      />
      <el-table-column
        property="schoolCondition"
        label="校企合作"
        align="center"
        width="120"
      />
      <el-table-column
        property="attendCondition"
        label="参加竞赛"
        align="center"
        width="120"
      />
      <el-table-column
        property="undertakeCondition"
        label="承办竞赛"
        align="center"
        width="120"
      />
      <el-table-column
        property="plan"
        label="投入计划"
        align="center"
        width="120"
      />
      <el-table-column
        property="remark"
        label="备注"
        align="center"
      />
      <el-table-column
        property="createBy"
        label="创建人"
        align="center"
        width="100"
      />
      <el-table-column
        property="createTime"
        label="创建时间"
        align="center"
        width="160"
        sortable
      />
      <el-table-column
        label="操作"
        align="center"
        v-if="$auth.hasPermi('md:department:edit') || $auth.hasPermi('md:department:remove')"
      >
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" v-hasPermi="['md:department:edit']" @click="openDialog(scope.row)">修改</el-button>
          <el-popconfirm
            confirm-button-text="是"
            cancel-button-text="否"
            title="确定删除吗？"
            @confirm="deleteHandler(scope.row)"
          >
            <el-button slot="reference" icon="el-icon-delete" type="text" v-hasPermi="['md:department:remove']" style="margin-left: 10px">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <div>
      <el-tabs>
        <el-tab-pane label="联系人" v-if="$auth.hasPermi('md:department:contact:list')">
          <Contacts v-if="schoolInfo.id" :school-info="schoolInfo" :type="0"/>
        </el-tab-pane>
      </el-tabs>
    </div>

    <el-dialog
      :title="dialogTitle === 1 ? '新增' : '修改'"
      :visible.sync="dialogVisible"
      width="500px"
      close-on-click-modal
      :fullscreen="device =='mobile'"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px" class="demo-form" :label-position="device =='mobile' ? 'top' : 'right'">
        <el-form-item label="二级部门" prop="name">
          <el-input v-model.trim="form.name" clearable :maxlength="50" placeholder="请输入二级部门"></el-input>
        </el-form-item>
        <el-form-item label="相关专业" prop="major">
          <el-input v-model.trim="form.major" type="textarea" clearable :maxlength="400" placeholder="请输入相关专业" :autosize="{ minRows: 2 }"></el-input>
        </el-form-item>
        <el-form-item label="参加竞赛" prop="attendCondition">
          <el-input v-model.trim="form.attendCondition" clearable :maxlength="200" placeholder="请输入参加竞赛"></el-input>
        </el-form-item>
        <el-form-item label="校企合作" prop="schoolCondition">
          <el-input v-model.trim="form.schoolCondition" clearable :maxlength="200" placeholder="请输入校企合作"></el-input>
        </el-form-item>
        <el-form-item label="承办竞赛" prop="undertakeCondition">
          <el-input v-model.trim="form.undertakeCondition" clearable :maxlength="200" placeholder="请输入承办竞赛"></el-input>
        </el-form-item>
        <el-form-item label="投入计划" prop="plan">
          <el-input v-model.trim="form.plan" clearable :maxlength="200" placeholder="请输入投入计划"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="form.remark" type="textarea" :maxlength="200" placeholder="请输入备注" :autosize="{ minRows: 2 }"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('formRef')">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import {addDataApi, deleteDataApi, getDataListApi, updateDataApi} from "@/api/crm/md/school";
import {getDataListApi as getAllClientListApi} from "@/api/crm/md/customer";
import ProvinceData from '@/views/crm/data/province.json'
import {getUserProfile} from "@/api/system/user";
import Contacts from "@/views/crm/md/contacts/index.vue";
import { mapGetters } from 'vuex'

export default {
  name: 'Department',
  dicts: ['sys_key_plan', 'sys_customer_type', 'sys_key_customer_basis'],
  components: { Contacts },
  props: ['customerInfo'],
  data() {
    return {
      // 记录上一次打开弹窗是修改or增加
      // null 增加
      // 非null 修改
      formId: null,
      // 加载动画
      loading: true,
      // 全部客户
      clientList: [],
      // 省份数据
      provinceList: [],
      // 弹框标题 1是增加 其他是修改
      dialogTitle: 1,
      // 弹框显示
      dialogVisible: false,
      // 新增和修改参数
      form: {
        attendCondition: "", // 参加竞赛情况
        clientId: null, // 客户id *
        clientName: "", // 客户名称
        createBy: "", // 用户 *
        createTime: "", // 创建时间 *
        id: null, // id
        major: "", // 相关专业
        name: "", // 二级部门名称 *
        plan: "", // 投入计划
        remark: "", // 备注
        schoolCondition: "", // 校企合作情况
        undertakeCondition: "", // 承办竞赛情况
        updateBy: "", // 更新人
        updateTime: "", // 更新时间
      },
      // 二级部门信息
      schoolInfo: {
        id: null
      },
      // 重点客户下拉数据
      isImportantList: [
        {
          value: 0,
          label: '普通客户'
        },
        {
          value: 1,
          label: '重点客户'
        }
      ],
      // 表单的校验规则
      rules: {
        name: [
          { required: true, message: '请填写二级部门名称', trigger: 'blur' }
        ],
        // isImportant: [
        //   { required: true, message: '请选择客户属性', trigger: 'change' }
        // ],
        // major: [
        //   { required: true, message: '请填写相关专业', trigger: 'blur' }
        // ],
        clientId: [
          { required: true, message: '请选择客户', trigger: 'change' }
        ],
      },
      // 表格数据
      tableData: [],
      // 总数条数
      total: 0,
      // 查询参数
      queryParams: {
        clientName: "", // 客户名称
        name: "", // 二级部门名称 *
        pageNum: 1,
        pageSize: 10,
      },
      // 用户信息
      user: {},
      roleGroup: {},
      postGroup: {},
    }
  },
  computed: {
    ...mapGetters([
      'device'
    ]),
  },
  watch: {
    customerInfo: {
      deep: true,
      handler(newV) {
        this.queryParams.clientId = newV.id
        this.getList()
      }
    },
    'form.isImportant': {
      handler(newV) {
        if(newV !== 1) {
          this.form.basis = null
        }
      }
    },
  },
  created() {
    this.provinceList = ProvinceData
    // this.getList()
    this.getUserinfo()
    this.getAllClientList()
  },
  methods: {
    async getAllClientList() {
      const res = await getAllClientListApi()
      this.clientList = res.rows
    },
    // 获取根据list中的value返回label
    getListValue(data, list, value = 'value') {
      let label = ''
      list.map((item) => {
        if(+item[value] === +data) {
          label = item.label
        }
      })
      return label
    },
    // 获取用户信息
    getUserinfo() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });
    },
    // 获取数据
    async getList() {
      this.loading = true
      const res = await getDataListApi(this.queryParams)
      if(res.code === 200) {
        this.tableData = res.rows
        this.total = res.total
      }
      this.loading = false
    },
    // 搜索的回调
    searchHandler() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 删除的回调
    async deleteHandler(row) {
      const res = await deleteDataApi({
        id: row.id
      })
      if(res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 打开弹窗
    openDialog(row) {
      if (row) {
        this.formId = row.id
        this.form = {...row}
        this.dialogTitle = 2
      } else {
        if(this.formId) {
          this.form = { ...this.$options.data().form }
        }

        this.formId = null
        this.dialogTitle = 1
      }
      this.dialogVisible = true
      this.form.clientId = this.customerInfo.id
      this.form.clientName = this.customerInfo.name
      // this.resetForm('formRef')
      this.$nextTick(()=>{
        this.$refs['formRef'].clearValidate();
        // this.resetForm('formRef')
      })
    },
    // 导出的回调
    async exportHandler() {
      this.download('crm/faculty/export', {
        ...this.queryParams,
        userId: this.user.userId,
        deptId: this.user.deptId,
      }, `faculty_${new Date().getTime()}.xlsx`)
    },
    // 表单提交
    submitForm(formName) {
      // if(this.form.isImportant === 1 && !(this.form.basis)) {
      //   this.$notify({
      //     title: '警告',
      //     message: '请选择重点依据',
      //     type: 'warning'
      //   });
      //   return false
      // }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.dialogTitle === 1) {
            this.addDataHandler()
          } else {
            this.updateDataHandler()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 增加数据的回调
    async addDataHandler() {
      const payload = {
        ...this.form,
        createBy: this.user.nickName,
        updateBy: this.user.nickName,
        userId: this.user.userId
      }
      const res = await addDataApi(payload)
      if(res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.formId = -1
        this.dialogVisible = false
        this.$refs.formRef.resetFields()
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 修改数据的回调
    async updateDataHandler() {
      const payload = {
        ...this.form,
        updateBy: this.user.nickName,
      }
      const res = await updateDataApi(payload)
      if(res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 重置表单
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
      this.form.clientId = this.customerInfo.id
      this.form.clientName = this.customerInfo.name
    },
    // 选中当前列
    handleCurrentChange(row) {
      this.schoolInfo = { ...row }
    },
  },
}
</script>
<style scoped lang="scss">
.oneLine {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
